package com.adnaan.admin.service.impl;

import com.adnaan.admin.mapper.SysRoleMapper;
import com.adnaan.admin.model.entity.SysRole;
import com.adnaan.admin.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统角色服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final JdbcTemplate jdbcTemplate;

    /**
     * 查询用户角色ID列表
     *
     * @param userId 用户ID
     * @return 角色ID列表
     */
    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        String sql = "SELECT role_id FROM sys_user_role WHERE user_id = ?";
        return jdbcTemplate.queryForList(sql, Long.class, userId);
    }

    /**
     * 分配用户角色
     *
     * @param userId  用户ID
     * @param roleIds 角色ID数组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignUserRoles(Long userId, Long[] roleIds) {
        // 删除原有角色关联
        String deleteSql = "DELETE FROM sys_user_role WHERE user_id = ?";
        jdbcTemplate.update(deleteSql, userId);

        // 添加新的角色关联
        if (roleIds != null && roleIds.length > 0) {
            List<Object[]> batchArgs = new ArrayList<>();
            for (Long roleId : roleIds) {
                batchArgs.add(new Object[]{userId, roleId});
            }

            String insertSql = "INSERT INTO sys_user_role(user_id, role_id) VALUES (?, ?)";
            jdbcTemplate.batchUpdate(insertSql, batchArgs);
        }
    }

    /**
     * 分配角色菜单权限
     *
     * @param roleId  角色ID
     * @param menuIds 菜单ID数组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoleMenus(Long roleId, Long[] menuIds) {
        // 删除原有菜单关联
        String deleteSql = "DELETE FROM sys_role_menu WHERE role_id = ?";
        jdbcTemplate.update(deleteSql, roleId);

        // 添加新的菜单关联
        if (menuIds != null && menuIds.length > 0) {
            List<Object[]> batchArgs = new ArrayList<>();
            for (Long menuId : menuIds) {
                batchArgs.add(new Object[]{roleId, menuId});
            }

            String insertSql = "INSERT INTO sys_role_menu(role_id, menu_id) VALUES (?, ?)";
            jdbcTemplate.batchUpdate(insertSql, batchArgs);
        }
    }
} 